// ignore_for_file: import_of_legacy_library_into_null_safe

import 'dart:convert';
import 'dart:io';
import 'package:flutter/services.dart';
import 'package:flutter/material.dart';
import 'package:fast_gbk/fast_gbk.dart';
import 'reader.dart';
import 'bookContentAnalyse.dart';
import '../db/booksManager.dart';
import 'dart:math' as math;

///   小说详情页面
class BookDetail extends StatefulWidget {
  BookDetail({Key? key}) : super(key: key);
  @override
  _BookDetailPageState createState() => _BookDetailPageState();
}

// 页面状态管理类
class _BookDetailPageState extends State<BookDetail> with SingleTickerProviderStateMixin {
  List<Map<String, Object?>> content = []; //内容
  List<Map<String, Object?>> firstChapter = [];
  List<String> menu = []; //菜单
  String path = ""; //路径
  String bookName = "";
  String contentTableName = "";
  final db = booksManager();
  double cachedWidth = 0;
  double cachedHeight = 0;
  bool loading = true;
  late final AnimationController _controller;

  // 获取路由传递的参数 book
  @override
  void didChangeDependencies() async {
    super.didChangeDependencies();
    // _dbinit();
    Object? book = ModalRoute.of(context)!.settings.arguments;

    if (book is Map<String, dynamic>) {
      path = book['path'];
      bookName = book['bookName'];
    }
  }

  // 状态初始化
  @override
  void initState() {
    super.initState();
    setTransparentStatusBar();
    _controller = AnimationController(
      vsync: this,
      duration: const Duration(seconds: 1),
    )..repeat(); // 使用repeat使其无限循环旋转
    // 初始化数据库
    _dbinit();
  }

  _dbinit() async {
    await db.initializeDatabase();
    bookOption();
  }

  // 文件操作
  bookOption() async {
    cachedWidth = MediaQuery.of(context).size.width * 0.8;
    cachedHeight = MediaQuery.of(context).size.height * 0.8;
    List<Map<String, Object?>> bookContentResult = await db.getBookInfo(bookName);
    contentTableName = bookContentResult[0]['content'].toString(); //获取表名
    final thisBookID = bookContentResult[0]['id'].toString(); //获取书籍id
    // List<Map<String, Object?>> contentTable = await db.getBookContent(contentTableName); //获取内容
    List<Map<String, Object?>> contentTable = await db.getBookContentByPage(contentTableName); //获取内容
    // print("测试数据库查询结果$contentTable");
    // print("object：$contentTableName");
    // 判断小说内容是否已经分析完成了
    // 先判断是否已经分析完成,没有就打开文件开始分析
    if (contentTable.length == 0) {
      // 读取文件
      // 打开文件以进行读取
      File file = File(path);
      String contentRead = '';
      var uniString = "";
      try {
        // 尝试用gbk编码来解码文件
        loading = true;
        setState(() {});
        contentRead = await file.readAsString(encoding: gbk);
        var unicode = utf8.encode(contentRead);
        uniString = utf8.decode(unicode);
      } catch (e) {
        // 如果使用gbk编码来解码文件报错，改用utf8编码来解码
        contentRead = await file.readAsString(encoding: utf8);
        var unicode = utf8.encode(contentRead);
        uniString = utf8.decode(unicode);
      } finally {
        // 调用BookContentAnalyse分析小说内容
        var analyzeFlag = BookContentAnalyse();
        await analyzeFlag.analyse(bookName, thisBookID.toString(), uniString, contentTableName);
        firstChapter = await db.getBookContentInfo(contentTableName, 0, 1);
        loading = false;
        setState(() {});
      }
    } else {
      //书籍分析完成
      firstChapter = await db.getBookContentInfo(contentTableName, 0, 1);
      loading = false;
      setState(() {});
    }
  }

// 导入小说的提示框
  noteWindow() {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text('导入失败'),
          content: Text('数据已存在'),
          actions: <Widget>[
            TextButton(
              child: Text('确定'),
              onPressed: () {
                Navigator.of(context).pop(); // 关闭对话框
              },
            ),
          ],
        );
      },
    );
  }

  // 设置状态栏透明
  void setTransparentStatusBar() {
    SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle(
      statusBarColor: Colors.transparent, // 设置状态栏颜色为透明
      statusBarIconBrightness: Brightness.dark, // 设置状态栏图标的亮度（可选）
    ));
  }

  // build
  @override
  Widget build(BuildContext context) {
    return AnnotatedRegion(
        child: Stack(
          children: [
            if (firstChapter.isNotEmpty) Reader(firstChapter: firstChapter, bookName: bookName, db: db, contengTableName: contentTableName, width: cachedWidth, height: cachedHeight),
            if (loading)
              Positioned(
                  top: 0,
                  bottom: 0,
                  left: 0,
                  right: 0,
                  child: Container(
                    // color: Color.fromARGB(255, 150, 202, 245),
                    child: Center(
                        child: AnimatedBuilder(
                      animation: _controller,
                      builder: (BuildContext context, Widget? child) {
                        return Transform.rotate(
                          angle: _controller.value * 2 * math.pi, // 角度范围0-2π
                          child: Container(
                            width: 100.0,
                            height: 100.0,
                            decoration: BoxDecoration(
                                borderRadius: BorderRadius.circular(100),
                                border: Border(
                                  top: BorderSide(
                                    // color: Color.fromARGB(255, 103, 169, 255),
                                    width: 3.0,
                                  ),
                                  bottom: BorderSide.none,
                                  left: BorderSide.none,
                                  right: BorderSide.none,
                                )),
                            // color: Colors.blue,
                            // child: FlutterLogo(size: 60),
                          ),
                        );
                      },
                    )),
                  )),
          ],
        ),
        value: SystemUiOverlayStyle(
          statusBarColor: Colors.transparent, // 设置状态栏颜色为透明
          systemNavigationBarColor: Colors.transparent, // 如果需要，同时设置导航栏颜色也为透明
        ));
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }
}
